<template>
  <div class="user">
    <page-search
      :searchFormConfig="searchFormConfig"
      @resetBtnClick="resetBtnClick"
      @searchBtnClick="searchBtnClick"
    ></page-search>
    <page-content
      :contentConfig="contentConfig"
      pageName="role"
      ref="pageContentRef"
      @newBtnClick="addClick"
      @editBtnClick="editClick"
    ></page-content>

    <page-modal
      ref="pageModalRef"
      pageName="role"
      :otherInfo="otherInfo"
      :defaultInfo="defaultInfo"
      :modalConfig="modalConfig">
      <div class="menu-tree">
        <el-tree
          :data="menus"
          ref="treeRef"
          node-key="id"
          show-checkbox
          @check="handleCheckChange"
          :props="{ children: 'children', label: 'name' }"
        ></el-tree>
      </div>
    </page-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, nextTick } from 'vue'
import { useStore } from '@/store'

import { ElTree } from 'element-plus'

import { menuToTreeKeys } from '@/utils/mapRoutes'

import { searchFormConfig } from './config/search.config'
import { contentConfig } from './config/content.config'
import { modalConfig } from './config/modal.config'

import PageSearch from '@/components/page-search/index'
import PageContent from '@/components/page-content/index'
import PageModal from '@/components/page-modal/index'

import { usePageSearch } from '@/hook/use-page-search'
import { usePageModal } from '@/hook/use-page-modal'

export default defineComponent({
  name: 'role',
  components: {
    PageSearch,
    PageContent,
    PageModal
  },
  setup() {
    // 重置/搜索 按钮点击-更新表格列表
    const [ pageContentRef, resetBtnClick, searchBtnClick ] = usePageSearch()
    
    const store = useStore()

    const menus = computed(() => store.state.login.roleMenus)

    const treeRef = ref<InstanceType<typeof ElTree>>()

    // 新增/编辑 按钮点击
    const editBtnClick = (item: any) => {
      const roleList =  menuToTreeKeys(item.menuList)

      nextTick(() => {
        treeRef.value?.setCheckedKeys(roleList, false)
      })
    }

    const otherInfo = ref({})
    const handleCheckChange = (data1: any, data2: any)  => {
      const checkedKeys = data2.checkedKeys
      const halfCheckedKeys = data2.halfCheckedKeys
      const menuList = [ ...checkedKeys, ...halfCheckedKeys ]
      otherInfo.value = { menuList }
    }

    const [ pageModalRef, defaultInfo, addClick, editClick ] = usePageModal(undefined, editBtnClick)
    

    return {
      searchFormConfig,
      contentConfig,
      modalConfig,
      defaultInfo,
      resetBtnClick,
      searchBtnClick,
      pageContentRef,
      pageModalRef,
      addClick,
      editClick,
      menus,
      treeRef,
      otherInfo,
      handleCheckChange
    }
  }
})
</script>

<style scoped lang="less">
.menu-tree {
  margin-left: 50px;
}
</style>